import {
  LoginLayout,
  MInput,
  MModal,
} from '@/views/login/components/LoginContainer.jsx';
import styled from 'styled-components';
import {Form, message} from 'antd';
import {getImageUrl, debounce} from '@/utils/utils.js';
import {useRef, useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {retrievePassword, sendSmscode} from '@/api/user.js';
import {b64_md5} from '@/utils/md5Ver2.2.js';

const ForgetContainer = styled.div`
    width: 480px;
    height: 580px;
    background: #fff;
    box-shadow: 0 0 25px #99989826;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-sizing: border-box;
    padding: 42px 51px 0px 51px;
    border-radius: 25px;
    overflow-y: auto;

    .code {
        color: #53b332;
        font-size: 14px;
        font-weight: 400;
        line-height: 12px;
        cursor: pointer;
    }

    .resetPass {
        color: #1c1c1c;
        font-size: 22px;
        font-weight: 400;
        line-height: 37.5px;
        text-align: center;
        margin-bottom: 49px;

    }

    .forget-btn {
        width: 100%;
        height: 56px;
        opacity: 0.8;
        font-size: 22px;
        font-weight: 400;
        color: #fff;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        background: linear-gradient(90deg, #06a0fd 0%, #37eab4 100%);

        &:hover {
            background: linear-gradient(90deg, #06a0fdce 0%, #37eab4ce 100%);
        }
    }

`;

function CodeBtn({isSendCode, countDown, sendCode}) {
  return (<>
    <div className="code" onClick={sendCode}>{isSendCode
        ? '发送验证码'
        : countDown + 's后可重新发送'}</div>
  </>);
}

function ForgetPage() {
  const [form] = Form.useForm();
  const formRef = useRef();
  const [isSendCode, setIsSendCode] = useState(true);
  const [countDown, setCountDown] = useState(60);
  const [isShowPwd, setIsShowPwd] = useState(true);
  const [isReShowPwd, setReIsShowPwd] = useState(true);
  const [isShowModal, setIsShowModal] = useState(false);
  const navigate = useNavigate();
  const password = Form.useWatch('password', form);
  const repassword = Form.useWatch('repassword', form);

  const sendCode = debounce(() => {
    if (!isSendCode) return;
    form.validateFields(['mobile']).then(async values => {
      // 验证通过
      const res = await sendSmscode(values.mobile, 3);
      if (res.result.status_info.status_code !== 100) {
        message.open({
          type: 'error',
          content: res.result.status_info.status_message,
        });
        return;
      }
      setIsSendCode(false);
      const timer = setInterval(() => {
        setCountDown((value) => {
          if (value === 0) {
            clearInterval(timer);
            setIsSendCode(true);
            return 60;
          }
          return value - 1;
        });
      }, 1000);
    }).catch(errorInfo => {
      // 验证失败
      console.log('验证失败:', errorInfo);
    });
  }, 200);

  function handleCancel() {
    setIsShowModal(false);
    navigate('/login');
  }

  function handleForget() {
    form.validateFields().then(async values => {
      console.log(values);
      const params = {
        mobile: values.mobile,
        sms_code: values.sms_code,
        password: b64_md5(values.password),
      };
      const res = await retrievePassword(params);
      if (res.result.status_info.status_code !== 100) {
        message.open({
          type: 'error',
          content: res.result.status_info.status_message,
        });
        return;
      }
      setIsShowModal(true);
    }).catch(errorInfo => {
      // 验证失败
      console.log('验证失败:', errorInfo);
    });
  }

  return (<>
    <LoginLayout>
      <ForgetContainer>

        <Form
            form={form}
            ref={formRef}>
          <div className="resetPass">重置密码</div>
          <Form.Item
              name="mobile"
              style={{marginBottom: '30px'}}
              validateTrigger="onBlur"
              rules={[
                {required: true, message: '请输入有效的手机号码'},
                {
                  validator: (_, value) => {
                    // const notNumberReg = /[^\d]+/g
                    const mobileReg = /^1[3-9][\d]{9}$/g; //手机号验证正则表达式
                    // if (value && notNumberReg.test(value)) {
                    //   form.setFieldValue(['mobile'], value.replace(notNumberReg, ''))
                    //   return Promise.reject(new Error('请输入有效的手机号码'));
                    // }
                    if (value && !mobileReg.test(value)) {
                      return Promise.reject(new Error('请输入有效的手机号码'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-phone" placeholder="请输入手机号码"
                    maxLength={11}></MInput>
          </Form.Item>
          <Form.Item
              name="sms_code"
              validateTrigger="onBlur"
              style={{marginBottom: '30px'}}
              rules={[
                {required: true, message: '验证码不能为空'},
                {
                  validator: (_, value) => {
                    // const notNumberReg = /[^\d]+/g
                    const vertificationCodeReg = /^[\d]{6}$/g; //验证码验证正则表达式
                    // if (value && notNumberReg.test(value)) {
                    //   form.setFieldValue(['code'], value.replace(notNumberReg, ''))
                    //   return Promise.reject(new Error('您输入的验证码错误，请重新输入'));
                    // }
                    if (value && !vertificationCodeReg.test(value)) {
                      return Promise.reject(
                          new Error('您输入的验证码错误，请重新输入'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-message" placeholder="请输入短信验证码"
                    maxLength={6}
                    suffix={<CodeBtn isSendCode={isSendCode}
                                     countDown={countDown}
                                     sendCode={sendCode}/>}></MInput>
          </Form.Item>
          <Form.Item
              name="password"
              style={{marginBottom: '30px'}}
              validateTrigger="onBlur"
              rules={[
                {required: true, message: '密码不能为空字符'},
                {
                  validator: (_, value) => {
                    const passwordReg = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,20}$|^(?=.*[a-zA-Z])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,20}$|^(?=.*[0-9])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,20}$/; //手机号验证正则表达式
                    if (value && !passwordReg.test(value)) {
                      return Promise.reject(new Error(
                          '格式错误，需含数字、字母和符号中至少2种，8-20位'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-lock"
                    placeholder="请设置密码（8-20位，数字＋字母或符号）"
                    type={isShowPwd ? 'password' : 'text'} suffix={password &&
                <img src={getImageUrl(
                    isShowPwd ? 'ic_eye_stop.png' : 'ic_eye.png')}
                     style={{width: '20px', height: '20px', cursor: 'pointer'}}
                     onClick={() => {
                       setIsShowPwd(!isShowPwd);
                     }}/>}></MInput>
          </Form.Item>
          <Form.Item
              name="repassword"
              style={{marginBottom: '40px'}}
              validateTrigger="onBlur"
              rules={[
                {required: true, message: '密码不能为空字符'},
                {
                  validator: (_, value) => {
                    const fPass = form.getFieldValue('password');
                    if (fPass !== value && value) {
                      return Promise.reject(new Error('两次输入密码不一致'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-lock" placeholder="请再次输入密码"
                    type={isReShowPwd ? 'password' : 'text'}
                    suffix={repassword &&
                        <img src={getImageUrl(
                            isReShowPwd ? 'ic_eye_stop.png' : 'ic_eye.png')}
                             style={{
                               width: '20px',
                               height: '20px',
                               cursor: 'pointer',
                             }} onClick={() => {
                          setReIsShowPwd(!isReShowPwd);
                        }}/>}></MInput>
          </Form.Item>
          <div className="forget-btn" onClick={handleForget}>下一步</div>
        </Form>
      </ForgetContainer>
      {isShowModal &&
          <MModal isModalOpen={isShowModal} handleCancel={handleCancel}
                  title="密码重置成功" tips="请妥善保管您的账户信息"
                  btnText="重写登录"/>}
    </LoginLayout>
  </>);
}

export default ForgetPage;